package com.example.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.common.util.constant.HospitalConstants;
import com.example.common.util.utils.DateUtils;
import com.example.common.util.utils.StringUtils;
import com.example.hospital.respository.DepartmentRepository;
import com.example.hospital.service.DepartmentService;
import com.example.model.domain.entity.hospital.Department;
import com.example.model.vo.hospital.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author juzipi
 * @Date 2021/5/5 19:51
 * @Info
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {


    @Autowired
    private DepartmentRepository departmentRepository;


    @Override
    public Boolean insertDepartment(Map<String, Object> map) {
        String string = JSONObject.toJSONString(map);
        Department department = JSONObject.parseObject(string, Department.class);
        //因为每个医院里都有科室吧，根据医院编号和对应的科室编号就能确定唯一的科室了
        Department departmentExists = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (StringUtils.isNotNull(departmentExists)){
            //非空就是更新
            departmentExists.setUpdateTime(DateUtils.getNowDate());
            Department update = departmentRepository.save(departmentExists);
            return true;
        }
        department.setCreateTime(DateUtils.getNowDate());
        department.setUpdateTime(department.getCreateTime());
        department.setDeleted(HospitalConstants.DELETED_VALUE_FALSE);
        Department save = departmentRepository.save(department);
        return true;
    }



    @Override
    public Page<Department> getDepartmentPage(Integer pageNum, Integer pageSize, String hoscode) {
        //mongodb的分页查询索引从0开始
        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        //这个department里面的数据就是查询条件
        Department department = new Department();
        department.setHoscode(hoscode);
        department.setDeleted(HospitalConstants.DELETED_VALUE_FALSE);
        //CONTAINING：包含，可能是类似模糊查询的吧，后面的是不区分大小写？
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        /*
        小结：mongoRepository的一些查询需要两个参数：一个是案例，一个是分页的，
        案例里有两个参数：一个是实体类（它会根据里面的属性去跟查询出的属性对比），一个是匹配器，匹配器可以设置匹配规则，比如包含，精确等
        分页就是springdata的了，感觉上没有pagehelper好用，没有过多的了解
         */
        return departmentRepository.findAll(Example.of(department, exampleMatcher), pageable);
    }

    @Override
    public Integer removeDepartment(String hoCode, String depCode) {
        return null;
    }

    /**
     * 根据hoscode和depcode删除department(逻辑删除)
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Boolean deleteDepartment(String hoscode, String depcode) {
        //逻辑删除
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        department.setDeleted(HospitalConstants.DELETED_VALUE_TRUE);
        department.setUpdateTime(DateUtils.getNowDate());
        departmentRepository.save(department);
        return true;
    }


    @Override
    public List<DepartmentVo> getDepartmentTree(String hoscode) {
        //最终结果
        ArrayList<DepartmentVo> result = new ArrayList<>();
        Department department = new Department();
        department.setHoscode(hoscode);
        List<Department> departments = departmentRepository.findAll(Example.of(department));
        //根据bigcode分组
        Map<String, List<Department>> departmentMap = departments.stream().collect(Collectors.groupingBy(Department::getBigcode));
        /*
        此处为：根据hoscode查出department集合，通过stream流来分组得到一个map集合
        遍历map集合，key为大科室的depcode，value为depname
        value里的值（就是List<Department>了） 就是小科室，再遍历value，分别设置depcode，depname
        最后就是封装返回了
         */
        departmentMap.forEach((k,v) -> {
            //大科室
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(k);
            departmentVo.setDepname(v.get(0).getBigname());
            //再遍历值 封装小科室
            ArrayList<DepartmentVo> children = new ArrayList<>();
            v.forEach(depart -> {
                DepartmentVo departmentVoChildren = new DepartmentVo();
                departmentVoChildren.setDepcode(depart.getDepcode());
                departmentVoChildren.setDepname(depart.getDepname());
                children.add(departmentVoChildren);
            });
            departmentVo.setChildren(children);
            //添加进最后返回的集合
            result.add(departmentVo);
        });
        return result;
    }


    @Override
    public Department getDepartmentByHoscodeAndDepcode(String hoscode,String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode,depcode);
    }


}
